﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Windows.Forms;

namespace ace_pso
{
     
    /// <summary>
    /// A <see cref="System.IO.TextWriter"/> that writes to a text box
    /// </summary>
    public class RichTextBoxWriter : TextWriter
    {
        private delegate void AppendTextDelegate(string message);

        void AppendText(string message)
        { 
            textBox.AppendText(message);
        }

        private delegate Font GetFontDelegate();

        private delegate void SetFontDelegate(Font font);

        private RichTextBox textBox;

        /// <summary>
        /// creates a new instance of the class
        /// </summary>
        /// <param name="b">The <see cref="TextBoxBase"/> that will be written to</param>
        public RichTextBoxWriter(RichTextBox b)
        {
            if (b == null)
                throw new NullReferenceException();

            textBox = b;
        }

        /// <summary>
        /// Get's the encoding of the stream
        /// </summary>
        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }
        }

        /// <summary>
        /// Write a string to the trace window
        /// </summary>
        /// <param name="message">The string to write</param>
        public override void Write(string message)
        {
            //message = " · " + message;
            if (textBox.InvokeRequired)
            {
                //if (textBox.Text.Length > 1 * 1024) textBox.Text = ""; 
                textBox.BeginInvoke(new AppendTextDelegate(AppendText), new object[] { message });
                //textBox.BeginInvoke(new AppendTextDelegate(textBox.AppendText), new object[] { message });
            }
            else
            {
                textBox.AppendText(message);
            }
        }

        Font spaceLineFont = new Font(FontFamily.GenericSansSerif, 5); 

        /// <summary>
        /// Writes a string and a new line to the text box
        /// </summary>
        /// <param name="message">The string to write</param>
        public override void WriteLine(string message)
        { 
            // 写入一个空行以调整行距 
            // 异步调用
            if (textBox.InvokeRequired)
            {
                Write(message + "\r\n"); 
                //IAsyncResult r = textBox.BeginInvoke(new GetFontDelegate(textBox.));
            } 
            else
            {
                Write(message);
                Font oldFont = textBox.Font;
                textBox.Font = spaceLineFont;
                textBox.AppendText("\r\n");
                textBox.Font = oldFont;
            }
        }
    }
}
